package com.cskaoyan.service;

import com.cskaoyan.bean.config.WxConfig;
import com.cskaoyan.bean.domain.*;
import com.cskaoyan.bean.goods.BasePageData;
import com.cskaoyan.bean.goods.GoodsDetailVo;
import com.cskaoyan.bean.goods.smallVo.CommentDetailVo;
import com.cskaoyan.bean.goods.wechat.*;
import com.cskaoyan.mapper.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * @BelongProject: mall35th
 * @BelongPackage: com.cskaoyan.service
 * @Author: zijin
 * @Createtime: 2021-12-03 星期五 15:28
 * @Description: todo
 */
@Service
public class WxUserServiceImpl implements WxUserService {
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    GoodsAttributeMapper attributeMapper;

    @Autowired
    BrandMapper brandMapper;

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    GrouponMapper grouponMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    IssueMapper issueMapper;

    @Autowired
    GoodsProductMapper goodsProductMapper;

    @Autowired
    GoodsSpecicationMapper goodsSpecicationMapper;

    @Autowired
    CollectMapper collectMapper;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    SearchHistoryMapper historyMapper;

    @Autowired
    FootPrintMapper footPrintMapper;

    @Override
    public UserOrderVo queryUserOrderMessage(Integer id) {
        UserOrderVo orderVo = new UserOrderVo();
        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria().andUserIdEqualTo(id);
        List<Order> orders = orderMapper.selectByExample(orderExample);
        int unship = 0,unrecv = 0,unpaid = 0,uncomment=0;
        for (Order order : orders) {
            switch(order.getOrderStatus()){
                /**
                 * 101即为待付款
                 * 201即为待收货
                 * 301即为待收货
                 * 401  402即为待评价
                 */
                case 101 :
                    unpaid++;
                    break; //可选
                case 201 :
                    unship++;
                    break; //可选
                case 301 :
                    unrecv++;
                    break; //可选
                case 401 :
                    uncomment++;
                    break; //可选
                case 402 :
                    uncomment++;
                    break; //可选
            }
        }
        orderVo.setUncomment(uncomment);
        orderVo.setUnpaid(unpaid);
        orderVo.setUnrecv(unrecv);
        orderVo.setUnship(unship);
        return orderVo;
    }

    /**
     * 根据商品id查询商品详情
     * @param id
     * @return
     */
    @Override
    public GoodsDetailVo queryGoodsDatails(Integer id) {
        GoodsDetailVo detailVo = new GoodsDetailVo();
        /**
         * 1.查询商品
         */
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andIdEqualTo(id);
        List<Goods> goods = goodsMapper.selectByExampleWithBLOBs(goodsExample);
        Goods good = null;
        if (goods.size() != 0){
            good = goods.get(0);
            detailVo.setInfo(good);
        }
        /**
         * 2.查询attributrs
         */
        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        goodsAttributeExample.createCriteria().andGoodsIdEqualTo(id);
        List<GoodsAttribute> goodsAttributes = attributeMapper.selectByExample(goodsAttributeExample);
        detailVo.setAttribute(goodsAttributes);

        /**
         * 3.查询品牌
         */
        BrandExample brandExample = new BrandExample();
        brandExample.createCriteria().andIdEqualTo(good.getBrandId());
        List<Brand> brands = brandMapper.selectByExample(brandExample);
        if (brands.size() != 0){
            detailVo.setBrand(brands.get(0));
        }else {
            Brand brand = new Brand();
            detailVo.setBrand(brand);
        }

        /**
         * 4.查询团购信息
         */
        Subject subject = SecurityUtils.getSubject();
        User user = null;
        if (subject.isAuthenticated()){
            user = (User) subject.getPrincipals().getPrimaryPrincipal();
            GrouponExample grouponExample = new GrouponExample();
            grouponExample.createCriteria().andUserIdEqualTo(user.getId());
            List<Groupon> groupons = grouponMapper.selectByExample(grouponExample);
            if (groupons.size() != 0){
                detailVo.setGroupon(groupons);
            }
        }else {
            ArrayList<Groupon> groupons = new ArrayList<>();
            detailVo.setGroupon(groupons);
        }

        /**
         * 5.查询issue信息
         */
        IssueExample issueExample = new IssueExample();
        List<Issue> issues = issueMapper.selectByExample(issueExample);
        if (issues.size() != 0){
            detailVo.setIssue(issues);
        }

        /**
         * 6.查询product信息
         */
        GoodsProductExample productExample = new GoodsProductExample();
        productExample.createCriteria().andGoodsIdEqualTo(id);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(productExample);
        if (goodsProducts.size() != 0){
            detailVo.setProductList(goodsProducts);
        }


        /**
         * 7.设置是否share和share地址
         */
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(new File("src/main/resources/config.properties")));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String market_wx_share = (String) properties.get("market_wx_share");
        detailVo.setShare(Boolean.valueOf(market_wx_share));
        if (good.getShareUrl() == null || "".equals(good.getShareUrl().trim())){
        }else {
            detailVo.setShareImage(good.getShareUrl());
        }

        /**
         * 8.查询specification
         * - 第一遍循环查询有多少个specficationName
         */
        GoodsSpecicationExample specicationExample = new GoodsSpecicationExample();
        specicationExample.createCriteria().andGoodsIdEqualTo(id);
        List<GoodsSpecication> goodsSpecications = goodsSpecicationMapper.selectByExample(specicationExample);
        /**
         * 写一个map
         */
        ArrayList<SpecificationByName> specificationByNameArrayList = new ArrayList<>();
        HashMap<String, List<GoodsSpecication>> listHashMap = new HashMap<>();
        if (goodsSpecications.size() != 0){
            for (GoodsSpecication specication : goodsSpecications) {
                if (listHashMap.get(specication.getSpecification()) == null){
                    /**
                     * 没有该类目的specification
                     */
                    ArrayList<GoodsSpecication> goodsSpecications1 = new ArrayList<>();
                    goodsSpecications1.add(specication);
                    listHashMap.put(specication.getSpecification(),goodsSpecications1);
                }else {
                    /**
                     * 如果已有该类目
                     */
                    listHashMap.get(specication.getSpecification()).add(specication);

                }
            }
            for (String s : listHashMap.keySet()) {
                SpecificationByName specificationByName = new SpecificationByName();
                specificationByName.setName(s);
                specificationByName.setValueList(listHashMap.get(s));
                specificationByNameArrayList.add(specificationByName);
            }
            detailVo.setSpecificationList(specificationByNameArrayList);
        }

        /**
         * 9.查询是否收藏
         */
        if(subject.isAuthenticated()){
            CollectExample collectExample = new CollectExample();
            byte type = 0;
            collectExample.createCriteria().andUserIdEqualTo(user.getId()).andTypeEqualTo(type).andValueIdEqualTo(id);
            List<Collect> collects = collectMapper.selectByExample(collectExample);
            if (collects.size() == 0){
                detailVo.setUserHasCollect(0);
            }else{
                detailVo.setUserHasCollect(1);
            }
        }

        /**
         * 10.查询评论
         */
        CommentExample commentExample = new CommentExample();
        byte flag = 0;
        commentExample.createCriteria().andTypeEqualTo(flag).andValueIdEqualTo(id);
        List<Comment> comments = commentMapper.selectByExample(commentExample);
        if (comments.size() != 0){
            CommentDetailVo commentDetailVo = new CommentDetailVo();
            commentDetailVo.setCount(comments.size());
            if (comments.size() > 2){
                List<Comment> comments1 = new ArrayList<>();
                comments1.add(comments.get(0));
                comments1.add(comments.get(1));
                commentDetailVo.setData(comments1);
            }else {
                commentDetailVo.setData(comments);
            }
            detailVo.setComment(commentDetailVo);
        }

        /**
        *@Description:
        * 11,查询商品，返回数据到会员足迹
        */
        if (subject.isAuthenticated()){
            FootPrint footPrint = new FootPrint();
            footPrint.setUserId(user.getId());
            footPrint.setGoodsId(id);
            footPrint.setAddTime(new Date());
            footPrint.setUpdateTime(new Date());
            footPrintMapper.insert(footPrint);
        }

        return detailVo;
    }

    @Override
    public int queryGoodsNum() {
        GoodsExample goodsExample = new GoodsExample();
        int num = (int) goodsMapper.countByExample(goodsExample);
        return num;
    }

    @Override
    public CategoryVo queryCategory(Integer id) {
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.createCriteria().andIdEqualTo(id);
        List<Category> categories = categoryMapper.selectByExample(categoryExample);
        Integer pid = categories.get(0).getPid();
        if (pid != 0){
            return queryCategorySecond(id);
        }else {
            CategoryExample categoryExample1 = new CategoryExample();
            categoryExample1.createCriteria().andPidEqualTo(id);
            categoryExample1.setOrderByClause("sort_order");
            List<Category> categories1 = categoryMapper.selectByExample(categoryExample1);
            return queryCategorySecond(categories1.get(0).getId());
        }
    }

    public CategoryVo queryCategorySecond(Integer id) {
        CategoryVo categoryVo = new CategoryVo();
        /**
         * 1.查询当前分类
         */
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.createCriteria().andIdEqualTo(id);
        List<Category> categories = categoryMapper.selectByExample(categoryExample);
        Category category = categories.get(0);
        categoryVo.setCurrentCategory(category);
        /**
         * 2.查询父分类
         */
        int pid = category.getPid();
        CategoryExample categoryExample1 = new CategoryExample();
        categoryExample1.createCriteria().andIdEqualTo(pid);
        List<Category> categories1 = categoryMapper.selectByExample(categoryExample1);
        if (categories1.size() != 0){
            categoryVo.setParentCategory(categories1.get(0));
        }
        /**
         * 3.查询兄弟分类
         */
        CategoryExample categoryExample2 = new CategoryExample();
        categoryExample2.createCriteria().andPidEqualTo(pid);
        List<Category> categories2 = categoryMapper.selectByExample(categoryExample2);
        categoryVo.setBrotherCategory(categories2);
        return categoryVo;
    }


    /**
     *categoryId等于0则为根据商品关键字进行模糊查询
     * @param categorySearchBean
     * @return
     */
    @Override
    public CategoryList queryGoodsByCategory(CategorySearchBean categorySearchBean) {
        PageHelper.startPage(categorySearchBean.getPage(),categorySearchBean.getLimit());
        Integer categoryId = categorySearchBean.getCategoryId();
        if (categoryId == 0){
            /**
             * 插入搜索记录到历史记录表
             */
            SearchHistory searchHistory = new SearchHistory();
            searchHistory.setAddTime(new Date());
            searchHistory.setUpdateTime(new Date());
            searchHistory.setKeyword(categorySearchBean.getKeyword());
            searchHistory.setFrom("Wx");
            searchHistory.setDeleted(false);
            Subject subject = SecurityUtils.getSubject();
            if (subject.isAuthenticated()){
                User user = (User) subject.getPrincipals().getPrimaryPrincipal();
                searchHistory.setUserId(user.getId());
            }
            historyMapper.insertSelective(searchHistory);


            GoodsExample goodsExample = new GoodsExample();
            GoodsExample.Criteria criteria = goodsExample.createCriteria();
            criteria.andNameLike("%" + categorySearchBean.getKeyword() + "%").andDeletedEqualTo(false).andIsOnSaleEqualTo(true);
            goodsExample.setOrderByClause(categorySearchBean.getSort() + " " + categorySearchBean.getOrder());
            List<Goods> goods = goodsMapper.selectByExample(goodsExample);
            PageInfo goodsInfo = new PageInfo<>(goods);
            CategoryList goodsBasePageData = new CategoryList();
            goodsBasePageData.setPage(goodsInfo.getPageNum());
            goodsBasePageData.setLimit(goodsInfo.getPageSize());
            goodsBasePageData.setPages(goodsInfo.getPages());
            goodsBasePageData.setTotal((int) goodsInfo.getTotal());
            goodsBasePageData.setList(goods);
            ArrayList<Category> categories = new ArrayList<>();
            goodsBasePageData.setFilterCategoryList(categories);
            return goodsBasePageData;
        }else {
            GoodsExample goodsExample = new GoodsExample();
            goodsExample.createCriteria().andCategoryIdEqualTo(categoryId).andDeletedEqualTo(false).andIsOnSaleEqualTo(true);
            goodsExample.setOrderByClause("sort_order");
            List<Goods> goods = goodsMapper.selectByExample(goodsExample);
            PageInfo goodsInfo = new PageInfo<>(goods);
            CategoryList goodsBasePageData = new CategoryList();
            goodsBasePageData.setPage(goodsInfo.getPageNum());
            goodsBasePageData.setLimit(goodsInfo.getPageSize());
            goodsBasePageData.setPages(goodsInfo.getPages());
            goodsBasePageData.setTotal((int) goodsInfo.getTotal());
            goodsBasePageData.setList(goods);
            ArrayList<Category> categories = new ArrayList<>();
            goodsBasePageData.setFilterCategoryList(categories);
            return goodsBasePageData;
        }
    }

    @Override
    public BasePageData<Goods> searchRelated(Integer id) {
        BasePageData<Goods> goodsBasePageData = new BasePageData<>();
        ArrayList<Goods> goods = new ArrayList<>();
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(new File("src/main/resources/config.properties")));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String market_wx_catlog_goods = (String) properties.get("market_wx_catlog_goods");
        Integer goodsNum = Integer.valueOf(market_wx_catlog_goods);
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andIdEqualTo(id);
        List<Goods> goods1 = goodsMapper.selectByExample(goodsExample);
        Integer categoryId = goods1.get(0).getCategoryId();
        /**
         * 根据目录id查询同类商品
         */
        GoodsExample goodsExample1 = new GoodsExample();
        goodsExample1.createCriteria().andCategoryIdEqualTo(categoryId);
        PageHelper.startPage(1,goodsNum);
        List<Goods> goods2 = goodsMapper.selectByExample(goodsExample1);
        PageInfo goodsInfo = new PageInfo<>(goods);
        goodsBasePageData.setLimit(goodsNum);
        goodsBasePageData.setPage(1);
        goodsBasePageData.setPages(goodsInfo.getPages());
        goodsBasePageData.setTotal((int) goodsInfo.getTotal());
        goodsBasePageData.setList(goods2);
        return goodsBasePageData;
    }


}
